package simulator.jsoncode;

import simulator.enums.EntityType;
import simulator.enums.Loop;
import simulator.types.Lane;

public class JSONEncoder
{
	public static final String LOOP_LANE_FIELD = "light";
	public static final String LOOP_TYPE_FIELD = "type";
	public static final String LOOP_WHICH_FIELD = "loop"; /* also send for bike/ped, use null in that case */
	public static final String LOOP_EMPTY_FIELD = "empty"; /* also send for bike/ped, use null in that case */
	public static final String LOOP_DESTINATION_FIELD = "to"; /* should only be needed for buses, send for everything anyways */
	
	public static final String MULTIPLIER_FIELD = "multiplier";
	
	private JSONEncoder()
	{}
	
	public static String getMultiplierString(int multi)
	{
		if(Integer.bitCount(multi) > 1)
		{
			System.err.println("Warning: multiplier string requested with non-power-of-two multiplier (out of spec)");
		}
		
		return "{\"" + MULTIPLIER_FIELD + "\":" + multi + "}";
	}

	public static String getLoopEvent(Lane from, EntityType type, Loop which, boolean empty, Lane dest)
	{
		StringBuilder jsonBuilder = new StringBuilder("[{");
		
		jsonBuilder.append(getKV(LOOP_LANE_FIELD, from.toString()) + ",");
		jsonBuilder.append(getKV(LOOP_TYPE_FIELD, type.getName()) + ",");
		
		if(type.hasLoops())
		{
			jsonBuilder.append(getKV(LOOP_WHICH_FIELD, which.getSpecString()) + ",");
			jsonBuilder.append(getKV(LOOP_EMPTY_FIELD, empty) + ",");
		}
		else
		{
			jsonBuilder.append(getKey_nullValue(LOOP_WHICH_FIELD) + ",");
			jsonBuilder.append(getKV(LOOP_EMPTY_FIELD, false) + ",");
		}
		
		
		jsonBuilder.append(getKV(LOOP_DESTINATION_FIELD, dest.toString()));
		
		jsonBuilder.append("}]");
		
		String le = jsonBuilder.toString();
		//System.out.println("Sending: " + le);
		return jsonBuilder.toString();
	}
	
	private static String getKV(String key, String value)
	{
		return "\"" + key + "\":\"" + value + "\"";
	}
	
	private static String getKV(String key, boolean value)
	{
		return "\"" + key + "\":" + Boolean.toString(value);
	}
	
	private static String getKey_nullValue(String key)
	{
		return "\"" + key + "\":\"close\"";
	}
}
